<?php
/**
 * Created by WarCraft3
 * User: WarCraft3
 * Date: 2021/8/20
 * Time: 14:14
 */

namespace app\api\controller;


use app\common\controller\Api;
use app\common\controller\Redis;
use fast\Http;
use think\Db;

class My extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    private $_uid;

    protected function _initialize()
    {
        parent::_initialize();
        $jwt = $this->request->header('Authorization');
        if ($jwt) {
            $this->check_token($jwt);
            $this->_uid = $this->_token['uid'];

        } else {
            $this->success('缺少token', '', '401');
        }
    }

    /*
     * 我的点赞->视频
     * */
    public function myzansVideos()
    {
        //1,先查找所有我的收藏的视频id
        $vids = Db::name('zans')->where('auser_id',$this->_uid)->column('avideo_id');
        if (!$vids){
            $this->error('无收藏视频');
        }
        //2,根据视频id , 查询所有的视频信息
        $videos = $this->getVideo($vids);
        $this->success('成功',$videos);
    }
    /*
     * 我的收藏->视频
     * */
    public function myVideos()
    {
        //1,先查找所有我的收藏的视频id
        $vids = Db::name('colles')->where('auser_id',$this->_uid)->column('avideo_id');
        if (!$vids){
            $this->error('无收藏视频');
        }
        //2,根据视频id , 查询所有的视频信息
        $videos = $this->getVideo($vids);
        $this->success('成功',$videos);
    }
    /*
     * 我的收藏->资料
     * */
    public function myFiles()
    {
        $files = Db::name('zansfile')->where('auser_id',$this->_uid)->column('avfile_id');
        if (!$files){
            $this->error('无收藏资料');
        }
        //根据文件id 查询所有文件
        $arr = Db::name('avfile')->whereIn('id',$files)->select();
        $this->success('成功',$arr);
    }

    /*
     * 我的奖状--每个学习/考试 阶段 对应一个奖状
     * */
    public function myCert()
    {
        $info = Db::name('auser')->where('id',$this->_uid)->field('name,avatar,ctime,longs')->find();
        $info['etime'] = date('Y-m-d H:i:s',time());
        $redis = Redis::getInstance()->getRedisConn();
        $re = $redis->hGetAll('user_'.$this->_uid);//已看完的全部视频id(其实应该筛选一下 value=1的才是全部看完的,但是我们没有保存value=0观看中的,所以现在只要进redis保存的都是已看完的)
        $info['study_count'] = sizeof($re);
        $re = array_keys($re);
        $avideo_ids=cate_avideo($this->_uid);//所有可看视频

        $periods = Db::name('period')->select()->toArray();
        foreach ($periods as $k=>$v){
            //查询是否看完阶段对应的所有视频, 如果已看完 显示学业证书,未看完则不显示
            $ids = Db::name('avideo')->where('period_id',$v['id'])->whereIn('id',$avideo_ids)->column('id');
            if ($ids == []){//如果阶段下面没有视频, 直接返回false
                unset($periods[$k]);
                continue;
            }
            $readed = array_intersect($ids,$re);//查找合集, 如果阶段ids 都在 已看完的readed中 , 那么说明 这个阶段的视频都看完了,可以获取对应的考试证书.
            if( $readed != $ids ){ //如果不相等, 说明没看完此阶段所有的视频id , 不可以生成证书
                unset($periods[$k]);
                continue;
            }
            $periods[$k]['ctime'] = Db::name('period')->where('id',$v['id'])->value('stime')??'';//阶段开始时间
            $periods[$k]['etime'] = Db::name('period')->where('id',$v['id'])->value('etime')??'';//阶段结束时间
            $periods[$k]['study_count'] = sizeof($ids);//阶段视频数
            $periods[$k]['username'] = $info['name'];
            $periods[$k]['avatar'] = $info['avatar'];
            $periods[$k]['ctime']=$periods[$k]['name'];
            $periods[$k]['etime']=$periods[$k]['name'];
            $duration=Db::name('avideo')->where('period_id',$v['id'])->sum('duration');
            $duration=toDate($duration);
            if(empty(floatval($duration[0]))&&!empty(floatval($duration[1]))){
                $longs=$duration[1].'分'.$duration[2].'秒';
            }elseif(empty(floatval($duration[0]))&&empty(floatval($duration[1]))){
                $longs=$duration[2].'秒';
            }else{
                $longs=$duration[0].'时'.$duration[1].'分'.$duration[2].'秒';
            }
            $periods[$k]['longs'] = $longs;//阶段学习时长, 用视频数乘以60s 大概就是学习时长,偷懒 懒得记录算了, 这个意义不大

            $periods[$k]['all'] = Db::name('exam_record')->where('auser_id',$this->_uid)->where('period_id',$v['id'])->count();
            $periods[$k]['pass'] = Db::name('exam_record')->where('auser_id',$this->_uid)->where('period_id',$v['id'])->where('ispass','1')->count();
            if ($periods[$k]['pass'] == 0 || $periods[$k]['all'] ==0 ){
                $periods[$k]['lv'] = '0%';
            }else{
                $periods[$k]['lv'] = round(($periods[$k]['pass'] / $periods[$k]['all']) * 100,2) ."%";
            }

        }
        $new = [];
        foreach ($periods as $k=>$v){
            $new[] = $v;
        }
        $info['list'] = $new;
        $this->success($info);
    }

    /*
     * 我的课程->我看过的视频 (包括 已看完 未观看)
     * */
    public function myClass()
    {
        $page = $this->request->param('page')??1;
        $num = $this->request->param('num')??20;
        $type = $this->request->param('type');
        $redis = Redis::getInstance()->getRedisConn();
        $avideo_ids=cate_avideo($this->_uid);
        $re = $redis->hGetAll('user_'.$this->_uid);
        $yesarr = [];
        if ($re){
            foreach ($re as $k=>$v){
                if(in_array($k,$avideo_ids)){
                    $yesarr[] = $k;
                }
            }
        }
        if($type=='wwc'){
            $arr=[];
            for($i=0;$i<count($avideo_ids);$i++){
                if(!in_array($avideo_ids[$i],$yesarr)){
                    $arr[]=$avideo_ids[$i];
                }
            }
        }else{
            $arr=$yesarr;
        }
        //2,根据视频id , 查询所有的视频信息
        $videos = $this->getVideo($arr,$page,$num);
        $this->success('成功',$videos);
    }

    /**
     * 搜索课程
     */
    public function search_Class()
    {
        $page = $this->request->param('page')??1;
        $num = $this->request->param('num')??20;
        $key = $this->request->param('keyword');
        $type = $this->request->param('type');
        $redis = Redis::getInstance()->getRedisConn();
        $avideo_ids=cate_avideo($this->_uid);
        $re = $redis->hGetAll('user_'.$this->_uid);
        $yesarr = [];
        if ($re){
            foreach ($re as $k=>$v){
                $yesarr[] = $k;
            }
        }
        if($type=='wwc'){
            $arr=[];
            for($i=0;$i<count($avideo_ids);$i++){
                if(!in_array($avideo_ids[$i],$yesarr)){
                    $arr[]=$avideo_ids[$i];
                }
            }
        }else{
            $arr=$yesarr;
        }
        //2,根据视频id , 查询所有的视频信息
        $videos = $this->getVideo($arr,$page,$num,$key);
        $this->success('成功',$videos);
    }
    /**
     * 我的成就
     * 统计“月”、“年”、“总”的“课程学习次数”、“考试次数”、“学分”、“积分”、“学习时间”五项情况
     */
    public function achievements(){
        $uid=$this->_uid;
        $ctime=Db::name('auser')->where('id',$uid)->value('ctime');
        $timestamp=strtotime($ctime);
        $startyear=date('Y/m/d',$timestamp);
        $ach[0]['start_time']=$startyear;
        $ach[0]['end_time']=date('Y/m/d',strtotime("+1 day",time()));
        $ach[0]['name']=date('y/m/d',$timestamp).'-'.date('y/m/d',time());
        $longs_hours=Db::name('point')->where('auser_id',$uid)->where('type',2)->where('ctime','>=', $ach[0]['start_time'])->where('ctime','<', $ach[0]['end_time'])->sum('longs');
        $ach[0]['longs_hours']=round($longs_hours/3600,2);
        $this->success('我的成就',$ach);
    }

    /**
     * @throws \think\Exception
     * 我的成就
     * $time_status:0=日,1=周,2=月,3=年,总
     */
    public function time_ach(){
        $uid=$this->_uid;
        $start_time=$this->request->param('start_time');
        $end_time=$this->request->param('end_time');
        $time_status=$this->request->param('time_status');
        if(empty($start_time)){
            $uid=$this->_uid;
            $ctime=Db::name('auser')->where('id',$uid)->value('ctime');
            $timestamp=strtotime($ctime);
            $start_time=date('Y/m/d',$timestamp);
        }
        if(empty($end_time)){
            $end_time=date('Y/m/d',strtotime("+1 day",time()));
        }

        $gettimes=$this->showMonthRange($start_time,$end_time);
        $period_ids=Db::name('period')->whereIn('name',$gettimes)->column('id');
        $avideo_ids=cate_avideo($uid);
        $learn_count=Db::name('point')->where('auser_id',$uid)->where('type',0)->where('ctime','>=', $start_time)->where('ctime','<', $end_time)->count();//总学习次数
        $exam_count=Db::name('exam_record')->where('auser_id',$uid)->where('ctime','>=', $start_time)->where('ctime','<', $end_time)->count();//考试次数

        if($time_status==0||$time_status==1){
            $biying_learn='';
            $biyi_learn='';
            $xuanying_learn='';
            $xuanyi_learn='';
            $tuiying_learn='';
            $tuiyi_learn='';
            $ying_exam='';
            $yi_exam='';
            $average='';
        }else{
            $all_avideo_ids= Db::name('avideo')->whereIn('id',$avideo_ids)->whereIn('period_id',$period_ids)->column('id');
            $biying_learn=Db::name('avideo')->where('type',0)->whereIn('id',$all_avideo_ids)->count();//必修应学习次数
            $biyi_learn =Db::name('point')->where('type',2)->where('xiu_type',0)->where('auser_id',$uid)->whereIn('avideo_id',$all_avideo_ids)->count();//必修已学习次数
            $xuanying_learn=Db::name('avideo')->where('type',1)->whereIn('id',$all_avideo_ids)->count();//选修应学习次数
            $xuanyi_learn =Db::name('point')->where('type',2)->where('xiu_type',1)->where('auser_id',$uid)->whereIn('avideo_id',$all_avideo_ids)->count();//选修已学习次数
            $tuiying_learn=Db::name('avideo')->where('type',2)->whereIn('id',$all_avideo_ids)->count();//推荐应学习次数
            $tuiyi_learn =Db::name('point')->where('type',2)->where('xiu_type',2)->where('auser_id',$uid)->whereIn('avideo_id',$all_avideo_ids)->count();//推荐已学习次数

            $all_exam_ids= Db::name('exam')->whereIn('avideo_id',$all_avideo_ids)->column('id');
            $ying_exam = Db::name('exam')->whereIn('id',$all_exam_ids)->count();//必修应考试次数
            $yi_exam = Db::name('exam_record')->where('auser_id',$uid)->where('ispass','1')->whereIn('id',$all_exam_ids)->count();//必修已考试次数
            $average=0;//必修考试平均分
        }

        $xuefen_count=Db::name('point')->where('auser_id',$uid)->where('type',1)->where('ctime','>=', $start_time)->where('ctime','<', $end_time)->sum('xuefen');//学分
        $jifen_count=Db::name('point')->where('auser_id',$uid)->where('type',0)->where('ctime','>=', $start_time)->where('ctime','<', $end_time)->sum('jifen');//积分
        $longs_count=Db::name('point')->where('auser_id',$uid)->where('type',2)->where('ctime','>=', $start_time)->where('ctime','<', $end_time)->sum('longs');//时长

        $bi_longs_count=Db::name('point')->where('auser_id',$uid)->where('type',2)->where('xiu_type',0)->where('ctime','>=', $start_time)->where('ctime','<', $end_time)->sum('longs');//必修时长
        $xuan_longs_count=Db::name('point')->where('auser_id',$uid)->where('type',2)->where('xiu_type',1)->where('ctime','>=', $start_time)->where('ctime','<', $end_time)->sum('longs');//选修时长
        $tui_longs_count=Db::name('point')->where('auser_id',$uid)->where('type',2)->where('xiu_type',2)->where('ctime','>=', $start_time)->where('ctime','<', $end_time)->sum('longs');//推荐时长


        $ach=array(
            'learn_count'=> (string)$learn_count,
            'biying_learn'=>(string)$biying_learn,
            'biyi_learn'=>(string)$biyi_learn,
            'xuanying_learn'=>(string)$xuanying_learn,
            'xuanyi_learn'=>(string)$xuanyi_learn,
            'tuiying_learn'=>(string)$tuiying_learn,
            'tuiyi_learn'=>(string)$tuiyi_learn,
            'ying_exam'=>(string)$ying_exam,
            'yi_exam'=>(string)$yi_exam,
            'average'=>(string)$average,

//            'gettimes'=>$gettimes,

            'exam_count'=> (string)$exam_count,
            'xuefen_count'=> (string)$xuefen_count,
            'jifen_count'=> (string)$jifen_count,
            'hour'=>toDate($longs_count)[0],
            'minute'=>$this->minute($longs_count),
            'bi_hour'=>toDate($bi_longs_count)[0],
            'bi_minute'=>$this->minute($bi_longs_count),
            'xuan_hour'=>toDate($xuan_longs_count)[0],
            'xuan_minute'=>$this->minute($xuan_longs_count),
            'tui_hour'=>toDate($tui_longs_count)[0],
            'tui_minute'=>$this->minute($tui_longs_count),
        );
        $this->success('我的成就',$ach);
    }

    /**
     * @param $longs_count
     * @return string
     * 获取时分秒
     */
    public function minute($longs_count){
        $minute=toDate($longs_count)[1];
        if(intval($minute)==0&&intval(toDate($longs_count)[0]==0)){
            if(intval(toDate($longs_count)[2])>0){
                $minute='01';
            }
        }
        return $minute;
    }

    /**
     * @param $start
     * @param $end
     * @return array
     * 获取时间段的月份
     */
    public function showMonthRange($start, $end)
    {
        $endtime=$end;
        $end = date('Y-m', strtotime($end)); // 转换为月
        $range = [];
        $i = 0;
        do {
            $month = date('Y-m', strtotime($start . ' + ' . $i . ' month'));
            $range[] = $month;
            $i++;
        } while ($month < $end);

        $mo=$range[count($range)-1];
        if(strtotime($mo.'-1 00:00:00')>=strtotime($endtime)){
            unset($range[count($range)-1]);
        }
        return $range;
    }
    /**
     * 获取创建账号开始到当前的年份
     */
    public function years(){
        $uid=$this->_uid;
        $ctime=Db::name('auser')->where('id',$uid)->value('ctime');
        $timestamp=strtotime($ctime);
        $startyear=$year=date('Y',$timestamp);
        $endtyear=date('Y',strtotime("+1 year",$timestamp));
        $nowyear=date('Y',time());
        $years[0]['start_time']=$year.'-1-1 00:00:00';
        $years[0]['end_time']=$endtyear.'-1-1 00:00:00';
        if($nowyear==$year){
            $years[0]['name']='本年';
        }else{
            $years[0]['name']=$year;
        }
        $longs_hours=Db::name('point')->where('auser_id',$uid)->where('type',2)->where('ctime','>=', $years[0]['start_time'])->where('ctime','<', $years[0]['end_time'])->sum('longs');
        $years[0]['longs_hours']=round($longs_hours/3600,2);
        for ($i=1;$i<=(intval($nowyear)-intval($startyear));$i++){
            $year++;
            $endtyear++;
            $years[$i]['start_time']=$year.'-1-1 00:00:00';
            $years[$i]['end_time']=$endtyear.'-1-1 00:00:00';
            $years[$i]['name']=$year;
            if($nowyear==$year){
                $years[$i]['name']='本年';
            }else{
                $years[$i]['name']=$year;
            }
            $longs_hours=Db::name('point')->where('auser_id',$uid)->where('type',2)->where('ctime','>=', $years[$i]['start_time'])->where('ctime','<', $years[$i]['end_time'])->sum('longs');
            $years[$i]['longs_hours']=round($longs_hours/3600,2);
        }
        $this->success('年份',$years);
    }

    /**
     * @return mixed
     * 获取创建到现在的月份
     */
    public function months(){
        $uid=$this->_uid;
        $ctime=Db::name('auser')->where('id',$uid)->value('ctime');
        $timestamp=strtotime($ctime);
        $startmonth=$month=$start_time=date('Y/m/d',$timestamp);
        $endtmonth=date('Y/m/d',strtotime("+1 month",$timestamp));
        $nowmonth=date('Y/m/d',time());
        $i = 0;
        if(date('Y/m',strtotime($nowmonth)).'/1 00:00:00'==date('Y/m',strtotime($start_time)).'/1 00:00:00'){
            $start_time= date('Y/m/d', strtotime('+' . $i . ' month', strtotime($startmonth)));
            $end_time = date('Y/m/d', strtotime('+' . $i . ' month', strtotime($endtmonth)));
            $tempDate['start_time']=date('Y/m',strtotime($start_time)).'/1 00:00:00';
            $tempDate['end_time']=date('Y/m',strtotime($end_time)).'/1 00:00:00';
            $tempDate['name']='本月';
            $wheretime=array();
            $wheretime['ctime']=['>=', $tempDate['start_time']];
            $wheretime['ctime']=['<', $tempDate['end_time']];
            $longs_hours=Db::name('point')->where('auser_id',$uid)->where('type',2)->where($wheretime)->sum('longs');
            unset($wheretime);
            $tempDate['longs_hours']=round($longs_hours/3600,2);
            $returnData[] = $tempDate;
        }else{
            while (strtotime(date('Y/m',strtotime($start_time)).'/1 00:00:00') < strtotime(date('Y/m',strtotime($nowmonth)).'/1 00:00:00')) {
                $start_time= date('Y/m/d', strtotime('+' . $i . ' month', strtotime($startmonth)));
                $end_time = date('Y/m/d', strtotime('+' . $i . ' month', strtotime($endtmonth)));
                $tempDate['start_time']=date('Y/m',strtotime($start_time)).'/1 00:00:00';
                $tempDate['end_time']=date('Y/m',strtotime($end_time)).'/1 00:00:00';
                if(date('Y/m',strtotime($nowmonth)).'/1 00:00:00'==date('Y/m',strtotime($start_time)).'/1 00:00:00'){
                    $tempDate['name']='本月';
                }else{
                    if(date('Y',time())==date('Y',strtotime($start_time))){
                        $tempDate['name']=date('m',strtotime($start_time));
                    }else{
                        $tempDate['name']=date('Y/m',strtotime($start_time));
                    }
                }
                $longs_hours=Db::name('point')->where('auser_id',$uid)->where('type',2)->where('ctime','>=', $tempDate['start_time'])->where('ctime','<', $tempDate['end_time'])->sum('longs');
                $tempDate['longs_hours']=round($longs_hours/3600,2);
                $returnData[] = $tempDate;
                $i++;
            }
        }
        $this->success('月份',$returnData);
    }
    /**
     * @return mixed
     * 获取创建到现在的周
     */
    public function weeks(){
        $uid=$this->_uid;
        $ctime=Db::name('auser')->where('id',$uid)->value('ctime');
        $weeks=array();
        if(date('w',strtotime($ctime))=='1'){
            $stime=strtotime($ctime);
        }else{
            $stime=strtotime('-1 week', strtotime($ctime));
        }
        for($i = strtotime('Monday',$stime); $i <= time(); $i = strtotime('+1 week', $i)){
            $weeks[]=date('Y/m/d', $i);
        }
        $onMonday=$this->onMonday();
        for ($i=0;$i<count($weeks);$i++) {
            $tempDate['start_time']=$weeks[$i].' 00:00:00';
            $tempDate['end_time']=date('Y/m/d', strtotime('+1 week', strtotime($weeks[$i]))).' 00:00:00';
            if($onMonday==$weeks[$i]){
                $tempDate['name']='本周';
            }else{
                if(date('Y',time())==date('Y',strtotime($weeks[$i]))){
                    $name=date('m/d',strtotime($weeks[$i]));
                    $name1=date('m/d',strtotime('+6 day', strtotime($weeks[$i])));
                }else{
                    $name=date('Y/m/d',strtotime($weeks[$i]));
                    $name1=date('Y/m/d',strtotime('+6 day', strtotime($weeks[$i])));
                }
                $tempDate['name']=$name.'-'.$name1;
            }
            $longs_hours=Db::name('point')->where('auser_id',$uid)->where('type',2)->where('ctime','>=', $tempDate['start_time'])->where('ctime','<', $tempDate['end_time'])->sum('longs');
            $tempDate['longs_hours']=round($longs_hours/3600,2);
            $returnData[] = $tempDate;
        }
        $this->success('每周',$returnData);
    }
    public function onMonday($type=1)
    {
        $weekday = date('w');
        if ($weekday == 0) {
            $weekday = 7;
        }
        $weekday = $weekday - 1;
        if ($type == 1) {
            return date("Y/m/d", strtotime("- {$weekday} days"));
        } else {
            return strtotime(date("Y/m/d", strtotime("- {$weekday} days")));
        }
    }
    /**
     * @return mixed
     * 获取创建到现在的日期
     */
    public function days(){
        $uid=$this->_uid;
        $ctime=Db::name('auser')->where('id',$uid)->value('ctime');
//        $timestamp=strtotime($ctime);
        $timestamp=strtotime("-30 day",time());
        $startdays=$days=$start_time=date('Y/m/d',$timestamp);
        $enddays=date('Y/m/d',strtotime("+1 day",$timestamp));
        $nowdays=date('Y/m/d',time());
        $i = 0;
        if($nowdays==$start_time){
            $start_time= date('Y/m/d', strtotime('+' . $i . ' day', strtotime($startdays)));
            $end_time = date('Y/m/d', strtotime('+' . $i . ' day', strtotime($enddays)));
            $tempDate['start_time']=$start_time.' 00:00:00';
            $tempDate['end_time']=$end_time.' 00:00:00';
            $tempDate['name']='本日';
            $longs_hours=Db::name('point')->where('auser_id',$uid)->where('type',2)->where('ctime','>=', $tempDate['start_time'])->where('ctime','<', $tempDate['end_time'])->sum('longs');
            $tempDate['longs_hours']=round($longs_hours/3600,2);
            $returnData[] = $tempDate;
        }else{
            while (strtotime($start_time) < strtotime($nowdays)) {
                $start_time= date('Y/m/d', strtotime('+' . $i . ' day', strtotime($startdays)));
                $end_time = date('Y/m/d', strtotime('+' . $i . ' day', strtotime($enddays)));
                $tempDate['start_time']=$start_time.' 00:00:00';
                $tempDate['end_time']=$end_time.' 00:00:00';
                if($nowdays==$start_time){
                    $tempDate['name']='本日';
                }else{
                    $tempDate['name']=date('d',strtotime($start_time));
                }
                $longs_hours=Db::name('point')->where('auser_id',$uid)->where('type',2)->where('ctime','>=', $tempDate['start_time'])->where('ctime','<', $tempDate['end_time'])->sum('longs');
                $tempDate['longs_hours']=round($longs_hours/3600,2);
                $returnData[] = $tempDate;
                $i++;
            }
        }
        $this->success('每日',$returnData);
    }
    /*
     * 积分排行榜/ 学分排行榜
     * */
    public function lists()
    {

        $page = $this->request->param('page')??1;
        $num = $this->request->param('num')??20;
        $type = $this->request->param('type'); // xue_fen =学分排行榜 ji_fen = 积分排行榜
        $sort_status=$this->request->param('sort_status');
        if($sort_status=='depart'){
            $uid=$this->_uid;
            $auser=Db::name('auser')->where('id',$uid)->find();
            $users = Db::name('auser')
                ->where('cate_id',$auser['cate_id'])
                ->field('name,avatar,catename,ji_fen,xue_fen')
                ->order($type,'desc')
                ->page($page,$num)
                ->select();
        }else{
            $pid=gongsi($this->_uid);
            $ids=pid_allcate($pid);
            $users = Db::name('auser')
                ->field('name,avatar,catename,ji_fen,xue_fen')
                ->order($type,'desc')
                ->whereIn('cate_id',$ids)
                ->page($page,$num)
                ->select();
        }
        $this->success('成功',$users);
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 本公司排名,本部门排名
     */
    public function ranking()
    {
        $type = $this->request->param('type'); // xue_fen =学分排行榜 ji_fen = 积分排行榜
        $uid=$this->_uid;
        $auser=Db::name('auser')->where('id',$uid)->find();
        $ausers = Db::name('auser')->field('id')->order($type,'desc')->select();
        foreach ($ausers as $k=>$v){
            if($ausers[$k]['id']==$uid){
                $auser['company_ranking']=$k+1;
            }
        }
        $users = Db::name('auser')->field('id')->where('cate_id',$auser['cate_id'])->order($type,'desc')->select();
        foreach ($users as $k=>$v){
            if($users[$k]['id']==$uid){
                $auser['department_ranking']=$k+1;
            }
        }
        $this->success('排名',$auser);
    }
    /*
     * 意见反馈
     * */
    public function fak()
    {
        $type = $this->request->param('type'); // 1= 课程需求反馈 2=意见反馈
        $arr['type'] = $type;
        $arr['ctime'] = time();
        $arr['auser_id'] = $this->_uid;
        $arr['intro'] = $this->request->param('intro');
        $ret = Db::name('fankui')->insert($arr);
        if ($ret) $this->success('反馈成功');
        $this->error('反馈失败');
    }

    /*
     * 获取视频信息---统一封装
     * @param $vids 视频ids
     *
     * */
    private function getVideo($vids,$page= 1 ,$num= 100,$key='')
    {
        $vidnots=is_del_avideo($this->_uid);
        $redis = Redis::getInstance()->getRedisConn();
        $re = $redis->hGetAll('user_'.$this->_uid);
        $vmodel = new \app\admin\model\Avideo();
        $data = $vmodel::with('com,category')
            ->where('avideo.name|avideo.intro','like','%'.$key.'%')
            ->whereIn('avideo.id',$vids)
            ->whereNotIn('avideo.id',$vidnots)
            ->page($page, $num)
            ->select()->each(function ($item)use($re){
                if (sizeof($item['com']) > 0) {
                    $item['comments'] = sizeof($item['com']);
                    //查询评论人信息
                    foreach ($item['com'] as $k => $v) {
                        $user = \app\admin\model\Auser::get($v['auser_id']);
                        $item['com'][$k]['name'] = $user['name'];
                        $item['com'][$k]['avatar'] = $user['avatar'];
                    }
                }else{
                    $item['comments'] = 0;
                }
                $item['ptype'] = '2'; // 0=观看中, 1=已看完 2=未观看
                //从redis中查询 观看与否的标签, 并匹配给每一条记录
                foreach ($re as $kk=>$vv){
                    if ($kk == $item['id']){
                        $item['ptype'] = $vv;
                    }
                }
                return $item;
            });
        return $data;
    }


    /*
     * 我的团队
     * */
    public function myteam()
    {
        $uid = $this->_uid;
        $gettime = $this->request->param('gettime'); //请求时间
        if(empty($gettime)){
            $gettime=date('Y-m',time());
        }
        $my = Db::name('auser')->where('id',$uid)->find();
        //查找当前部门 所有负责人 的 所有下级
        if ($my['role'] == '0'){
            $this->error('无下级人员');
        }
        //2,查找我的部门分类下面的所有人员
        $users = Db::name('auser')->where('cate_id',$my['cate_id'])->field('id,name,avatar,xue_fen,ji_fen,longs,cate_id')->select()->each(function ($item) use ($gettime){
            $avideo_ids=cate_avideo($item['id']);
            if(empty($gettime)){
                $item['yingcheng']=Db::name('avideo')->where('type',0)->whereIn('id',$avideo_ids)->count();
                $okkecheng =Db::name('point')->where('type',1)->count();
                $item['nocheng'] =intval($item['yingcheng'])-intval($okkecheng);
                //考试次数 / 通过次数
                $item['all'] = Db::name('exam')->where('avideo_id',$avideo_ids)->count();
                $pass = Db::name('exam_record')->where('auser_id',$item['id'])->where('ispass','1')->count();
                $item['no_pass']=intval($item['all'])-intval($pass);
            }else{
                $time=date('Y-m',strtotime($gettime));
                $starttime=$time.'-01 00:00:00';
                if($time==date('Y-m',time())){
                    $wheretime['ctime']=['>', $starttime];
                }else{
                    $endtime = date('Y-m', strtotime('+1 month', strtotime($gettime)));
                    $endtime = $endtime . '-01 00:00:00';
                    $wheretime['ctime'] = ['between', [$starttime, $endtime]];
                }
                //考试次数 / 通过次数
                $period_id=Db::name('period')->where('name',$gettime)->value('id');
                $all_avideo_ids= Db::name('avideo')->whereIn('id',$avideo_ids)->where('period_id',$period_id)->column('id');
                $all_exam_ids= Db::name('exam')->whereIn('avideo_id',$all_avideo_ids)->column('id');

                $ji_fen1 =Db::name('point')->where('type',0)->where('auser_id',$item['id'])->whereIn('avideo_id',$all_avideo_ids)->sum('jifen');
                $ji_fen2=Db::name('point')->where('type',0)->where('auser_id',$item['id'])->whereIn('exam_id',$all_exam_ids)->sum('jifen');
                $item['ji_fen']=$ji_fen1+$ji_fen2;

                $xue_fen1 =Db::name('point')->where('type',1)->where('auser_id',$item['id'])->whereIn('avideo_id',$all_avideo_ids)->sum('xuefen');
                $xue_fen2 =Db::name('point')->where('type',1)->where('auser_id',$item['id'])->whereIn('exam_id',$all_exam_ids)->sum('xuefen');
                $item['xue_fen']=$xue_fen1+$xue_fen2;

//                    学习任务
                $item['yingcheng']=Db::name('avideo')->where('type',0)->whereIn('id',$avideo_ids)->where('period_id',$period_id)->count();
                $okkecheng =Db::name('point')->where('type',1)->where('auser_id',$item['id'])->whereIn('avideo_id',$all_avideo_ids)->count();
                $item['nocheng'] =intval($item['yingcheng'])-intval($okkecheng);
                if($item['nocheng']!=0){
                    $item['weiwancheng_status']='1';
                }else{
                    $item['weiwancheng_status']='0';
                }
//                    考试
                $item['all'] = Db::name('exam')->whereIn('avideo_id',$avideo_ids)->where('period_id',$period_id)->count();
                $pass = Db::name('exam_record')->where('auser_id',$item['id'])->where('ispass','1')->whereIn('id',$all_exam_ids)->count();
                $item['no_pass']=intval($item['all'])-intval($pass);
                if($item['no_pass']!=0){
                    $item['weitongguo_status']='1';
                }else{
                    $item['weitongguo_status']='0';
                }
            }
            return $item;
        });
        if(strtotime($gettime.'-01 00:00:00')>mktime(0,0,0,date('m'),1,date('Y'))){
            $users=[];
        }
        $data['users'] = $users;
        $data['catename'] = Db::name('category')->where('id',$my['cate_id'])->value('name');
        $data['count'] = (string)count($users);
        $weiwancheng=0;
        $weitongguo=0;
        foreach ($users as $k=>$v){
            if($users[$k]['nocheng']!=0){
                $weiwancheng++;
            }
            if($users[$k]['no_pass']!=0){
                $weitongguo++;
            }
        }
        $data['weiwancheng'] =(string)$weiwancheng;
        $data['weitongguo'] = (string)$weitongguo;
        $data['date'] = date('Y-m');
        $this->success('成功',$data);
    }

    /*
     * 我的团队->导出excel表格
     * */
    public function outExcel()
    {
        $uid = $this->_uid;
        $gettime = $this->request->param('gettime'); //请求时间
        $cid = $this->request->param('cid');//部门id
        if(empty($gettime)){
            $gettime=date('Y-m',time());
        }
        if(strtotime($gettime.'-01 00:00:00')>mktime(0,0,0,date('m'),1,date('Y'))){
            $this->error('无数据');
        }
        $my = Db::name('auser')->where('id',$uid)->find();
        if(!$cid){
            $cid=$my['cate_id'];
        }
        if(empty($cid)){
            $this->error('参数错误');
        }
        //查找当前部门 所有负责人 的 所有下级
        if ($my['role'] == '0'){
            //$this->error('无下级人员');
        }
        //2,查找我的部门分类下面的所有人员
        $users = Db::name('auser')->where('cate_id',$cid)->field('id,name,avatar,xue_fen,ji_fen,longs,cate_id')->select()
            ->each(function ($item) use ($gettime){
                $avideo_ids=cate_avideo($item['id']);
                if(empty($gettime)){
                    $item['yingcheng']=Db::name('avideo')->where('type',0)->whereIn('id',$avideo_ids)->count();
                    $okkecheng =Db::name('point')->where('type',1)->count();
                    $item['nocheng'] =intval($item['yingcheng'])-intval($okkecheng);
                    //考试次数 / 通过次数
                    $item['all'] = Db::name('exam')->whereIn('avideo_id',$avideo_ids)->count();
                    $pass = Db::name('exam_record')->where('auser_id',$item['id'])->where('ispass','1')->count();
                    $item['no_pass']=intval($item['all'])-intval($pass);
                }else{
                    $time=date('Y-m',strtotime($gettime));
                    $starttime=$time.'-01 00:00:00';
                    if($time==date('Y-m',time())){
                        $wheretime['ctime']=['>', $starttime];
                    }else{
                        $endtime=date('Y-m',strtotime('+1 month',strtotime($gettime)));
                        $endtime=$endtime.'-01 00:00:00';
                        $wheretime['ctime']=['between', [$starttime,$endtime]];
                    }
                    $period_id=Db::name('period')->where('name',$gettime)->value('id');
                    $all_exam_ids= Db::name('exam')->whereIn('avideo_id',$avideo_ids)->where('period_id',$period_id)->column('id');
                    $all_avideo_ids= Db::name('avideo')->whereIn('id',$avideo_ids)->where('period_id',$period_id)->column('id');

                    $ji_fen1 =Db::name('point')->where('type',0)->where('auser_id',$item['id'])->whereIn('avideo_id',$all_avideo_ids)->sum('jifen');
                    $ji_fen2=Db::name('point')->where('type',0)->where('auser_id',$item['id'])->whereIn('exam_id',$all_exam_ids)->sum('jifen');
                    $item['ji_fen']=$ji_fen1+$ji_fen2;

                    $xue_fen1 =Db::name('point')->where('type',1)->where('auser_id',$item['id'])->whereIn('avideo_id',$all_avideo_ids)->sum('xuefen');
                    $xue_fen2 =Db::name('point')->where('type',1)->where('auser_id',$item['id'])->whereIn('exam_id',$all_exam_ids)->sum('xuefen');
                    $item['xue_fen']=$xue_fen1+$xue_fen2;

//                    学习任务
                    $item['yingcheng']=Db::name('avideo')->where('type',0)->whereIn('id',$avideo_ids)->where('period_id',$period_id)->count();
                    $okkecheng =Db::name('point')->where('type',1)->where('auser_id',$item['id'])->whereIn('avideo_id',$all_avideo_ids)->count();
                    $item['nocheng'] =intval($item['yingcheng'])-intval($okkecheng);

//                    考试
                    $item['all'] = Db::name('exam')->whereIn('avideo_id',$avideo_ids)->where('period_id',$period_id)->count();
                    $pass = Db::name('exam_record')->where('auser_id',$item['id'])->where('ispass','1')->whereIn('id',$all_exam_ids)->count();
                    $item['no_pass']=intval($item['all'])-intval($pass);
                    if(empty($item['all'])){
                        $item['pass_rate']='0%';
                    }else{
                        $item['pass_rate']=round($pass/$item['all']*100,2).'%';
                    }

                }
                return $item;
            });

        // Create new Spreadsheet object
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $catename = Db::name('auser')->where('id',$this->_uid)->value('catename');
        if(empty($gettime)){
            $title=$catename.'学习情况';
        }else{
            $title=$catename.$gettime.'学习情况';
        }
        $sheet->setCellValue( 'A1', $title);
        $sheet->setCellValue( 'A2', '姓名');
        $sheet->setCellValue( 'B2', '学分');
        $sheet->setCellValue( 'C2', '积分');
        $sheet->setCellValue( 'D2', '应完成课程');
        $sheet->setCellValue( 'E2', '未完成课程');
        $sheet->setCellValue( 'F2', '应考试次数');
        $sheet->setCellValue( 'G2', '未通过考试');
        $sheet->setCellValue( 'H2', '通过率');
        $i = 3;
        foreach ($users  as $k=>$v){

            $sheet->setCellValue( 'A'.$i, $v['name']);
            $sheet->setCellValue( 'B'.$i, $v['xue_fen']);
            $sheet->setCellValue( 'C'.$i, $v['ji_fen']);
            $sheet->setCellValue( 'D'.$i, $v['yingcheng']);
            $sheet->setCellValue( 'E'.$i, $v['nocheng']);
            $sheet->setCellValue( 'F'.$i, $v['all']);
            $sheet->setCellValue( 'G'.$i, $v['no_pass']);
            $sheet->setCellValue( 'H'.$i, $v['pass_rate']);
            $i++;
        }

        // Save
        $date = date('Y-m-d-His',time());
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('uploads/excel/'.$title.'.xlsx');
        $url = 'https://'.$_SERVER['SERVER_NAME'].'/uploads/excel/'.$title.'.xlsx';
        $this->success('成功',$url);
    }

    /*
     * 判断是否绑定
     * */
    public function isbind()
    {
        $job = Db::name('auser')->where('id',$this->_uid)->value('cate_id');
        if ($job){
            $this->success('已绑定');
        }else{
            $this->error('未绑定');
        }
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 学习地图,考试列表，只返回4个字段
     */
    public function study_avideo(){
        $redis = Redis::getInstance()->getRedisConn();

        $gettime = $this->request->param('gettime');
        if(empty($gettime)){
            $gettime=date('Y-m',time());
        }
        $period_id=Db::name('period')->where('name',$gettime)->value('id');

        $avideo_ids=cate_avideo($this->_uid);
        $vidnots=is_del_avideo($this->_uid);
        $re = $redis->hGetAll('user_'.$this->_uid);
        $arr = Db::name('avideo')
            ->whereNotIn('id',$vidnots)
            ->whereIn('id',$avideo_ids)
            ->where('period_id',$period_id)
            ->order('weigh desc')
            ->select()->each(function ($item) use($re) {
                $item1['ptype'] = '0'; // 0=观看中, 1=已看完 2=未观看
                //从redis中查询 观看与否的标签, 并匹配给每一条记录
                foreach ($re as $kk=>$vv){
                    if ($kk == $item['id']){
                        $item1['ptype'] = $vv;
                    }
                }
                $item1['id']=$item['id'];
                if($item['type']==0){
                    $item1['xiu']='必修';
                }elseif($item['type']==1){
                    $item1['xiu']='选修';
                }elseif($item['type']==2){
                    $item1['xiu']='推荐';
                }
                $item1['name']=$item['name'];
                $item1['lasttime']=$item['lasttime'];
                return $item1;
            })->toArray();
        $wtg=[];
        $ytg=[];
        foreach ($arr as $k=>$v){
            if($arr[$k]['ptype']=='0'){
                $wtg[]=$arr[$k];
            }else{
                $ytg[]=$arr[$k];
            }
        }
        $att['wtg']=$arr;
        $att['ytg']=$ytg;
        $this->success('已绑定',$att);
    }
    /*
* 模糊搜索视频
* */
    public function seavideo()
    {
        $key = $this->request->param('keyword');
        if (!$key)$this->error('缺少参数');
        $ptype_status = $this->request->param('ptype_status');
        $redis = Redis::getInstance()->getRedisConn();
        $avideo_ids=cate_avideo($this->_uid);
        $vidnots=is_del_avideo($this->_uid);
        $re = $redis->hGetAll('user_'.$this->_uid);
        $arr = Db::name('avideo')
            ->where('name','like','%'.$key.'%')
            ->whereNotIn('id',$vidnots)
            ->whereIn('id',$avideo_ids)
            ->order('weigh desc')
            ->select()->each(function ($item) use($re) {
                $item1['ptype'] = '0'; // 0=观看中, 1=已看完 2=未观看
                //从redis中查询 观看与否的标签, 并匹配给每一条记录
                foreach ($re as $kk=>$vv){
                    if ($kk == $item['id']){
                        $item1['ptype'] = $vv;
                    }
                }
                $item1['id']=$item['id'];
                if($item['type']==0){
                    $item1['xiu']='必修';
                }elseif($item['type']==1){
                    $item1['xiu']='选修';
                }elseif($item['type']==2){
                    $item1['xiu']='推荐';
                }
                $item1['name']=$item['name'];
                $item1['lasttime']=$item['lasttime'];
                return $item1;
            })->toArray();
        $wtg=[];
        $ytg=[];
        foreach ($arr as $k=>$v){
            if($arr[$k]['ptype']=='0'){
                $wtg[]=$arr[$k];
            }else{
                $ytg[]=$arr[$k];
            }
        }
        if($ptype_status=='wtg'){
            if(empty($arr)){
                $str='';
            }else{
                $str=$arr[0]['id'];
            }
        }else{
            if(empty($ytg)){
                $str='';
            }else{
                $str=$ytg[0]['id'];
            }
        }
        $this->success('搜索地图',$str);
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 按照月份显示该月所有视频。
     */
    public function period_video()
    {
        $gettime = $this->request->param('gettime');
        if (!$gettime)$this->error('缺少参数');
        $period_id=Db::name('period')->where('name',$gettime)->value('id');
        $redis = Redis::getInstance()->getRedisConn();
        $avideo_ids=cate_avideo($this->_uid);
        $vidnots=is_del_avideo($this->_uid);
        $re = $redis->hGetAll('user_'.$this->_uid);
        $arr = Db::name('avideo')
            ->where('period_id',$period_id)
            ->whereNotIn('id',$vidnots)
            ->whereIn('id',$avideo_ids)
            ->order('weigh desc')
            ->select()->each(function ($item) use($re) {
                $item1['ptype'] = '0'; // 0=观看中, 1=已看完 2=未观看
                //从redis中查询 观看与否的标签, 并匹配给每一条记录
                foreach ($re as $kk=>$vv){
                    if ($kk == $item['id']){
                        $item1['ptype'] = $vv;
                    }
                }
                $item1['id']=$item['id'];
                if($item['type']==0){
                    $item1['xiu']='必修';
                }elseif($item['type']==1){
                    $item1['xiu']='选修';
                }elseif($item['type']==2){
                    $item1['xiu']='推荐';
                }
                $item1['name']=$item['name'];
                $item1['lasttime']=$item['lasttime'];
                return $item1;
            })->toArray();

        $wtg=[];
        $ytg=[];
        foreach ($arr as $k=>$v){
            if($arr[$k]['ptype']=='0'){
                $wtg[]=$arr[$k];
            }else{
                $ytg[]=$arr[$k];
            }
        }
//        $att['wtg']=$arr;
//        $att['ytg']=$ytg;
        $this->success('搜索地图',$arr);
    }
    /**
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 获取用户头像和昵称
     */
    public function wx_login_name()
    {
        $uid = $this->_uid;
        $avatarUrl = $this->request->param("avatar")??'1';
        $nickName = $this->request->param("name")??'1';

        $personnel_find = Db::name('auser')->where("id", $uid)->find();
        if (!empty($personnel_find)) {
            //获取当前昵称
            $personnel_data['name'] = $nickName;
            //获取当前头像
            $personnel_data['avatar'] = $avatarUrl;
            //执行添加操作
            Db::name('auser')->where("id", $uid)->update($personnel_data);
        }
        $auser=Db::name('auser')->where("id", $uid)->find();
        $this->success('用户信息',$auser);
    }
    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 学习地图,考试列表,正在使用,简单处理
     */
    public function study_exam(){
        $uid = $this->_uid;
        $avideo_ids=cate_avideo($this->_uid);
        $gettime = $this->request->param('gettime');
        if(empty($gettime)){
            $gettime=date('Y-m',time());
        }
        $period_id=Db::name('period')->where('name',$gettime)->value('id');
        $arr = Db::name('avideo')
            ->whereIn('id',$avideo_ids)
            ->where('period_id',$period_id)
            ->order('weigh desc')
            ->select();
        $att=[];
        foreach ($arr as $k=>$v){
            $exam=Db::name('exam')->where('avideo_id',$arr[$k]['id'])->find();
            if($exam&&!in_array($exam['id'],is_del_exam($uid))){
                $demo = new Demo();
                $exam['exam_item']=$demo->exam_items($exam['id']);
                $exam['lasttime']=$exam['endtime'];
                $exam['ptype'] = Db::name('exam_record')->where(['auser_id'=>$this->_uid])->where(['exam_id'=>$exam['id']])->value('ispass');
                if(empty($exam['ptype'])){
                    $exam['ptype']='0';
                }
                $att[]=$exam;
            }
        }
        $wtg=[];
        $ytg=[];
        foreach ($att as $k=>$v){
            if($att[$k]['ptype']=='0'){
                $wtg[]=$att[$k];
            }else{
                $ytg[]=$att[$k];
            }
        }
        $app['wtg']=$att;
        $app['ytg']=$ytg;
        $this->success('成功',$app);
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 学习地图,考试列表,正在使用,简单处理
     */
    public function se_exam(){
        $key = $this->request->param('keyword');
        if (!$key)$this->error('缺少参数');
        $ptype_status = $this->request->param('ptype_status');
        $uid = $this->_uid;
        $avideo_ids=cate_avideo($this->_uid);
        $exams=Db::name('exam')->whereIn('avideo_id',$avideo_ids)->whereNotIn('id',is_del_exam($uid))->where('name','like','%'.$key.'%')->select()->toArray();
        $wtg=[];
        $ytg=[];
        $att=[];
        if($exams){
            foreach ($exams as $k=>$v){
                $exams[$k]['lasttime']=$exams[$k]['endtime'];
                $exams[$k]['ptype'] = Db::name('exam_record')->where(['auser_id'=>$this->_uid])->where(['exam_id'=>$exams[$k]['id']])->value('ispass');
                if(empty($exams[$k]['ptype'])){
                    $exams[$k]['ptype']='0';
                }
                $att[]=$exams[$k];
            }
            foreach ($att as $k=>$v){
                if($att[$k]['ptype']=='0'){
                    $wtg[]=$att[$k];
                }else{
                    $ytg[]=$att[$k];
                }
            }
        }
        if($ptype_status=='wtg'){
            if(empty($att)){
                $str='';
            }else{
                $str=$att[0]['id'];
            }
        }else{
            if(empty($ytg)){
                $str='';
            }else{
                $str=$ytg[0]['id'];
            }
        }
        $this->success('搜索考试地图',$str);
    }
    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 按照月份显示该月所有试题。
     */
    public function period_exam(){
        $gettime = $this->request->param('gettime');
        if (!$gettime)$this->error('缺少参数');
        $uid = $this->_uid;
        $avideo_ids=cate_avideo($this->_uid);
        $period_id=Db::name('period')->where('name',$gettime)->value('id');
        $arr = Db::name('avideo')
            ->whereIn('id',$avideo_ids)
            ->where('period_id',$period_id)
            ->order('weigh desc')
            ->select();
        $att=[];
        foreach ($arr as $k=>$v){
            $exam=Db::name('exam')->where('avideo_id',$arr[$k]['id'])->find();
            if($exam&&!in_array($exam['id'],is_del_exam($uid))){
                $demo = new Demo();
                $exam['exam_item']=$demo->exam_items($exam['id']);
                $exam['lasttime']=$exam['endtime'];
                $exam['ptype'] = Db::name('exam_record')->where(['auser_id'=>$this->_uid])->where(['exam_id'=>$exam['id']])->value('ispass');
                if(empty($exam['ptype'])){
                    $exam['ptype']='0';
                }
                $att[]=$exam;
            }
        }
        $wtg=[];
        $ytg=[];
        foreach ($att as $k=>$v){
            if($att[$k]['ptype']=='0'){
                $wtg[]=$att[$k];
            }else{
                $ytg[]=$att[$k];
            }
        }
//        $app['wtg']=$att;
//        $app['ytg']=$ytg;
        $this->success('搜索考试地图',$att);
    }
    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取考试列表,notpass:未通过,undo:未考试,passed:已通过
     */
    public function all_exams()
    {
        $uid = $this->_uid;
        $whereperiod = '';
        $avideo_ids=cate_avideo($this->_uid);
        //根据cid 查询未通过中的未测试的考试
        $result = [];
        $demo = new Demo();
        //未通过---不及格的 考试
        $notrecord = Db::name('exam_record')->where(['auser_id'=>$uid,'ispass'=>'0'])->column('exam_id');
        $examnots=is_del_exam($uid);
        $notpass1 = Db::name('exam')
            ->whereIn('id',$notrecord)
            ->where($whereperiod)
            ->whereIn('avideo_id',$avideo_ids)->select()->each(function ($item) use ($demo){
                $item['exam_item'] = $demo->exam_items($item['id']);
                return $item;
            });
        $result['notpass'] = $notpass1??[];

        $already = Db::name('exam_record')->where(['auser_id'=>$uid])->column('exam_id');

        //未测试的考试
        $undo = Db::name('exam')
            ->whereNotIn('id',$already)
            ->whereIn('avideo_id',$avideo_ids)
            ->where($whereperiod)
            ->select()->each(function ($item) use ($demo){
                $item['exam_item'] = $demo->exam_items($item['id']);
                return $item;
            });
        $result['undo'] = $undo??[];

        //已通过的考试
        $passed = Db::name('exam_record')->where(['auser_id'=>$uid,'ispass'=> '1'])->column('exam_id');
        $pass = Db::name('exam')
            ->whereIn('id',$passed)
            ->whereNotIn('id',$examnots)
            ->whereIn('avideo_id',$avideo_ids)
            ->where($whereperiod)
            ->select()->each(function ($item) use ($demo){
                $item['exam_item'] = $demo->exam_items($item['id']);
                return $item;
            });
        $result['passed'] = $pass;

        $this->success('成功',$result);
    }
    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 学习地图,视频,显示全部信息
     */
    public function allvideos(){
        $page = $this->request->param('page');
        $num = $this->request->param('num');
        if(!$page){
            $page= 1;
        }
        if(!$num){
            $num= 10;
        }
        $redis = Redis::getInstance()->getRedisConn();
        $avideo_ids=cate_avideo($this->_uid);
        $vidnots=is_del_avideo($this->_uid);
        $re = $redis->hGetAll('user_'.$this->_uid);
        $vmodel = new \app\admin\model\Avideo();
        $arr = $vmodel::with('com,category')
            ->whereNotIn('avideo.id',$vidnots)
            ->whereIn('avideo.id',$avideo_ids)
//            ->page($page, $num)
            ->select()->each(function ($item) use($re) {
                if (sizeof($item['com']) > 0) {
                    $item['comments'] = sizeof($item['com']);
                    //查询评论人信息
                    foreach ($item['com'] as $k => $v) {
                        $user = \app\admin\model\Auser::get($v['auser_id']);
                        $item['com'][$k]['name'] = $user['name'];
                        $item['com'][$k]['avatar'] = $user['avatar'];
                    }
                    $coms=$item['com'];
                    $commms=[];
                    foreach ($item['com'] as $k => $v){
                        if($item['com'][$k]['pid']>0){
                            unset($item['com'][$k]);
                        }else{
                            $arr=[];
                            foreach ($coms as $ve) {
                                if ($ve['pid'] == $item['com'][$k]['id']) {
                                    $arr[] = $ve;
                                };
                            };
                            $item['com'][$k]['children']=$arr;
                            $commms[]=$item['com'][$k];
                        }
                    }
                    $item['com']=$commms;
                }else{
                    $item['comments'] = 0;
                }
                $item['ptype'] = '0'; // 0=观看中, 1=已看完 2=未观看
                //从redis中查询 观看与否的标签, 并匹配给每一条记录
                foreach ($re as $kk=>$vv){
                    if ($kk == $item['id']){
                        $item['ptype'] = $vv;
                    }
                }
                return $item;
            })->toArray();
        //根据排序 未观看的在最上面 0=观看中, 1=已看完 2=未观看
        $cmf_arr = array_column($arr, 'ptype');
        array_multisort($cmf_arr, SORT_DESC, $arr);
        $this->success('成功',$arr);
    }
    /*
     * 考试--资料库
     * */
    public function allfiles()
    {
        $where = [];
        $cate_id = $this->request->param('cate_id')??0;
        $page = $this->request->param('page')??1;
        $num = $this->request->param('num')??20;
        $key = $this->request->param('keyword');
        if ($cate_id){
            $where = ['cate_id'=>$cate_id];
        }
        $ret = Db::name('avfile')
            ->whereLike('name','%'.$key.'%','like')
            ->where($where)
            ->page($page,$num)
            ->select()->each(function ($item){
                $is = Db::name('zansfile')->where(['auser_id'=>$this->_uid,'avfile_id'=>$item['id']])->find();
                $item['iszan'] = 0;
                if($is){
                    $item['iszan'] = 1;
                }
                return $item;
            });
        $this->success('成功',$ret);
    }

    /*
     * 获取考试完毕后的排行榜
     * */
    public function paim()
    {
        $eid = $this->request->param('exam_id');
        $vmodel = new \app\admin\model\ExamRecord();
        $data = $vmodel::with('auser')
//        $data = Db::name('exam_record')
            ->where('exam_id',$eid)
            ->order('point desc')
            ->select()->each(function ($item){
                $userinfo = Db::name('auser')->where('id',$item['auser_id'])->find();
                $item['name'] = $userinfo['name']??'';
                $item['avatar'] = $userinfo['avatar']??'';
                return $item;
            });
        $ret['paiming'] = ords($this->_uid,$eid);
        $ret['data'] = $data;
        $ret['point'] = Db::name('exam_record')->where('exam_id',$eid)->where('auser_id',$this->_uid)->value('point');
        $ret['avatar'] = Db::name('auser')->where('id',$this->_uid)->value('avatar');
        $this->success('ok',$ret);
    }

}